package com.eascs.workflow.wf.service.impl;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.workflow.common.entity.wf.ProcessNodeTemplate;
import com.eascs.workflow.wf.dao.ProcessNodeTemplateDao;
import com.eascs.workflow.wf.entity.UpdateNodeTemplateOrderNoEntity;
import com.eascs.workflow.wf.service.ProcessNodeTemplateService;
import com.eascs.workflow.wf.vo.MoveTemplateNodeOpt;

@Service
public class ProcessNodeTemplateServiceImpl implements ProcessNodeTemplateService {
	private final int ORDER_STEP = 10;

	@Inject
	private ProcessNodeTemplateDao processNodeTemplateDao;

	@Override
	public List<Object[]> findNodeTemplatesByProcessId(String processId) {
		return processNodeTemplateDao.findNodeTemplatesByProcessId(processId);
	}

	@Override
	@Transactional(transactionManager = "wfTransactionManager")
	public void moveTemplateNode(String nodeId, String moveTemplateNodeOpt, String updator) {
		ProcessNodeTemplate processNodeTemplate = processNodeTemplateDao.getById(ProcessNodeTemplate.class, nodeId);
		List<ProcessNodeTemplate> processNodeTemplates = processNodeTemplateDao.getByProcessId(processNodeTemplate.getProcessNo());
		// set order no
		for (int i = 0; i < processNodeTemplates.size(); i++) {
			processNodeTemplates.get(i).setOrderNo(i * ORDER_STEP);
		}
		// update current node order
		for (int i = 0; i < processNodeTemplates.size(); i++) {
			ProcessNodeTemplate processNodeTemplateItem = processNodeTemplates.get(i);
			if (!nodeId.equals(processNodeTemplateItem.getNodeId()))
				continue;
			int orderNo = processNodeTemplateItem.getOrderNo();
			if (MoveTemplateNodeOpt.UP.equals(moveTemplateNodeOpt)) {
				orderNo = orderNo - ORDER_STEP - 1;
			} else {
				orderNo = orderNo + ORDER_STEP + 1;
			}
			processNodeTemplateItem.setOrderNo(orderNo);
		}

		// resort and rest set order no
		processNodeTemplateDao.sortNodeTemplate(processNodeTemplates);
		for (int i = 0; i < processNodeTemplates.size(); i++) {
			processNodeTemplates.get(i).setOrderNo((i + 1) * ORDER_STEP);
		}

		// update to db
		for (int i = 0; i < processNodeTemplates.size(); i++) {
			ProcessNodeTemplate processNodeTemplateItem = processNodeTemplates.get(i);
			UpdateNodeTemplateOrderNoEntity updateNodeTemplateOrderNoEntity = new UpdateNodeTemplateOrderNoEntity();
			updateNodeTemplateOrderNoEntity.setNodeId(processNodeTemplateItem.getNodeId());
			updateNodeTemplateOrderNoEntity.setOrderNo(processNodeTemplateItem.getOrderNo());
			updateNodeTemplateOrderNoEntity.setUpdateTime(new Date());
			updateNodeTemplateOrderNoEntity.setUpdator(updator);
			this.processNodeTemplateDao.updateById(updateNodeTemplateOrderNoEntity);
		}

	}

}
